/**
 * @description axios二次封装
 */
import axios from 'axios'
import config from './../config'
import { ElMessage } from 'element-plus'
import route from '../router'
import storage from './storage'
const ENVCODE_MESSAGE = {
  0: '登录错误，请重试',
  1: '网络异常,请稍后重试',
  2: '账号或密码不正确',
  3: 'Toke认证失败,请重新登录!',
}
// 创建实例，添加全局配置
const service = axios.create({
  baseURL: config.baseApi,
  timeout: 8000,
})
// 请求拦截
service.interceptors.request.use((req) => {
  const headers = req.headers
  const { token } = storage.getItem('userInfo') || {}
  if (!headers.Authorization) headers.Authorization = 'Bearer ' + token
  return req
})

//响应拦截
service.interceptors.response.use((res) => {
  const { code, data, msg } = res.data
  if (code === 200 || code == 0) {
    return data
  } else if (code === 50001) {
    ElMessage.error(ENVCODE_MESSAGE[3])
    setTimeout(async () => {
      const router = await route()
      router.push('/login')
    }, 2000)
    return Promise.reject(ENVCODE_MESSAGE[0])
  } else {
    ElMessage.error(msg || ENVCODE_MESSAGE[1])
    return Promise.reject(msg || ENVCODE_MESSAGE[1])
  }
})
/**
 * 请求核心函数
 * @param {String} url:请求地址
 * @param {String} method:请求方法 post || get
 * @param {Object} data:携带数据
 * @param {boolean} mock:开启mockapi
 */
function request(options) {
  options.method = options.method || 'get'
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data
  }
  // 局部mock
  if (typeof options.mock !== undefined) {
    config.mock = options.mock
  }
  if (config.env === 'production') {
    service.defaults.baseURL = config.baseApi
  } else {
    service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
  }
  return service(options)
}

;['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
  request[item] = (url, data, options) => {
    return request({
      url,
      data,
      method: item,
      ...options,
    })
  }
})

export default request
